import { Component, OnInit, ViewChild } from '@angular/core';
import { NzFormatEmitEvent, NzTreeNode, NzNotificationService, NzMessageService, NzModalService } from 'ng-zorro-antd';
import { _HttpClient, SettingsService } from '@delon/theme';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { replaceKeysDeep } from '@shared';
import { SFSchema, SFComponent } from '@delon/form';

/**
 * 部门管理
 */
@Component({
  selector: 'deptment-basic',
  templateUrl: './deptment-basic.component.html',
  styleUrls: ['./deptment-basic.component.less'],
})
export class DeptmentBasicComponent implements OnInit {
  constructor(
    private http: _HttpClient,
    private notice: NzNotificationService,
    private msg: NzMessageService,
    private modal: NzModalService,
    private settings: SettingsService,
  ) {}
  searchValue = '';
  nodes = [];
  activedNode: NzTreeNode;
  curDept: { [key: string]: any } = {};
  showAdd = false;
  loading = false;
  showEditBtn = false;
  auth_dept_add = false;
  auth_dept_edit = false;
  auth_dept_del = false;

  @ViewChild('sf', { static: false }) sf: SFComponent;

  mapShortToLong = {
    id: 'key',
    name: 'title',
  };
  schemaForAdd: SFSchema = {
    properties: {
      parentId: {
        type: 'string',
        title: '父级id',
        ui: {
          hidden: true,
        },
      },
      deptCode: {
        type: 'string',
        title: '部门编码',
        ui: {
          placeholder: '部门编码',
        },
      },
      name: {
        type: 'string',
        title: '部门名称',
        ui: {
          placeholder: '部门名称',
        },
      },
      sort: { type: 'number', title: '排序', default: 1 },
    },
    required: ['deptCode', 'name', 'parentId'],
  };
  schema: SFSchema = {
    properties: {
      deptId: {
        type: 'string',
        title: '部门id',
        ui: {
          hidden: true,
        },
      },
      parentId: {
        type: 'string',
        title: '父级id',
        ui: {
          hidden: true,
        },
      },
      tenantId: {
        type: 'string',
        title: '租户id',
        ui: {
          hidden: true,
        },
      },
      delFlag: {
        type: 'string',
        title: '状态',
        ui: {
          hidden: true,
        },
      },
      deptCode: {
        type: 'string',
        title: '部门编码',
        readOnly: true,
        ui: {
          placeholder: '部门编码',
        },
      },
      name: {
        type: 'string',
        title: '部门名称',
        readOnly: true,
        ui: {
          placeholder: '部门名称',
        },
      },
      sort: { type: 'number', title: '排序', readOnly: true, default: 1 },
    },
    required: ['deptCode', 'name'],
  };

  ngOnInit() {
    this.loadDeptTree();
    this.auth_dept_add = this.settings.user.permissions.sys_dept_add;
    this.auth_dept_edit = this.settings.user.permissions.sys_dept_edit;
    this.auth_dept_del = this.settings.user.permissions.sys_dept_del;
  }

  loadDeptTree() {
    this.http
      .get('/cf/admin/dept/tree')
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(data => {
        this.nodes = [];
        const o: [] = replaceKeysDeep(data.data, this.mapShortToLong);
        o.forEach(r => {
          this.nodes.push(r);
        });
      });
  }

  getDept(id) {
    this.loading = true;
    this.http
      .get(`/cf/admin/dept/${id}`)
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(data => {
        this.loading = false;
        if (data.status === 200) {
          this.curDept = data.data;
          this.schema.properties.deptId.default = this.curDept.deptId;
          this.schema.properties.parentId.default = this.curDept.parentId;
          this.schema.properties.tenantId.default = this.curDept.tenantId;
          this.schema.properties.delFlag.default = this.curDept.delFlag;
          this.schema.properties.deptCode.default = this.curDept.deptCode;
          this.schema.properties.name.default = this.curDept.name;
          this.schema.properties.sort.default = this.curDept.sort;
          this.sf.refreshSchema();
        }
      });
  }

  reset() {
    this.schema.properties.deptId.default = null;
    this.schema.properties.parentId.default = '0';
    this.schema.properties.tenantId.default = null;
    this.schema.properties.delFlag.default = '0';
    this.schema.properties.deptCode.default = null;
    this.schema.properties.name.default = null;
    this.schema.properties.sort.default = 1;
    this.sf.refreshSchema();
  }

  resetForAdd(parentId) {
    this.schemaForAdd.properties.parentId.default = parentId;
    this.schemaForAdd.properties.deptCode.default = null;
    this.schemaForAdd.properties.name.default = null;
    this.schemaForAdd.properties.sort.default = 1;
    this.sf.refreshSchema();
  }

  /**
   * 显示添加框
   */
  showAddForm(e) {
    // 先取消编辑
    this.closeEdit();
    if (!this.showAdd) {
      this.resetForAdd(this.curDept.deptId || '0');
      this.showAdd = true;
    }
    e.stopPropagation();
    e.preventDefault();
  }
  cancel() {
    this.showAdd = false;
  }
  /**
   * 显示编辑框
   */
  startEdit(e) {
    // 先取消添加
    this.cancel();
    this.showAdd = false;
    this.showEditBtn = true;
    this.schema.properties.deptCode.readOnly = false;
    this.schema.properties.name.readOnly = false;
    this.schema.properties.sort.readOnly = false;
    this.sf.refreshSchema();
    e.stopPropagation();
    e.preventDefault();
  }
  /**
   * 关闭编辑
   */
  closeEdit(willReload = true) {
    this.showEditBtn = false;
    this.schema.properties.deptCode.readOnly = true;
    this.schema.properties.name.readOnly = true;
    this.schema.properties.sort.readOnly = true;
    this.sf.refreshSchema();
    if (willReload && this.activedNode) {
      this.getDept(this.activedNode.key);
    }
  }

  nzEvent(event: NzFormatEmitEvent): void {
    if (event.eventName === 'click') {
      if (event.node.isSelected) {
        this.getDept(event.node.key);
        if (this.activedNode && this.activedNode.key !== event.node.key) {
          this.closeEdit(false);
        }
      }
      this.activedNode = event.node!;
      this.showAdd = false;
    }
  }

  /**
   * 删除部门
   */
  delDept(e) {
    if (this.curDept.deptId) {
      this.modal.confirm({
        nzTitle: `确定删除 ${this.curDept.name} ?`,
        nzOnOk: () => {
          this.http.delete(`/cf/admin/dept/${this.curDept.deptId}`).subscribe(res => {
            if (res.status === 200) {
              this.notice.success('提示', '删除成功');
              this.loadDeptTree();
              this.reset();
              this.curDept = {};
            }
          });
        },
      });
    }
    e.stopPropagation();
    e.preventDefault();
  }

  /**
   * 修改部门
   */
  sfSubmit(value: any) {
    this.loading = true;
    this.http
      .put('/cf/admin/dept/', value)
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(res => {
        this.loading = false;
        if (res.status === 200) {
          this.notice.success('提示', '提交成功');
          this.loadDeptTree();
        }
      });
  }

  /**
   * 添加部门
   */
  sfSubmitForAdd(value: any) {
    this.loading = true;
    this.http
      .post('/cf/admin/dept/', value)
      .pipe(catchError(err => of(err)))
      .subscribe(res => {
        this.loading = false;

        if (res.status === 200) {
          this.notice.success('提示', '提交成功');
          this.loadDeptTree();
          this.resetForAdd(this.curDept.deptId || '0');
        }
      });
  }
}
